﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NHibernate.Linq;
using System.Reflection;
using NHibernate;

namespace HibernateDynamicData.Adapter
{
    public class GenericNHibernateContext : NHibernateContext
    {
        private ISession session;

        private string rootNamespace;

        public GenericNHibernateContext()
        {
            this.rootNamespace = "TestData";
            this.session = NHibernateFactory.Current.OpenSession();
        }

        protected override ISession ProvideSession()
        {
            return session;
        }

        public object GetTable(string entityName)
        {
            string fullEntityName = String.Concat(rootNamespace, ".", entityName);
            var clazz = NHibernateFactory.Current.Configuration.GetClassMapping(fullEntityName).MappedClass;
            var mi = typeof(NHibernateExtensions).GetMethod("Linq", new Type[] { typeof(ISession) }).MakeGenericMethod(clazz);
            return mi.Invoke(null, new object[] { session });
        }
    }
}
